﻿#region Usings

using System.Collections.Specialized;
using System.IO;
using System.Xml.XPath;
using Kazkommertsbank.Framework.Common;
using Kazkommertsbank.Framework.Model;
using Kazkommertsbank.Framework.Model.Pay;

#endregion

namespace Kazkommertsbank.Framework
{
    public class KkbResponseParameters : RequestFormWrapper
    {
        public KkbResponseParameters()
        {}

        public KkbResponseParameters(NameValueCollection requestForm) : base(requestForm)
        {}

        // ReSharper disable InconsistentNaming
        public string response { get; set; }
        // ReSharper restore InconsistentNaming

        public ResponseDocumentBase GetKazkommertsbankResponse()
        {
            if(!string.IsNullOrEmpty(response))
            {
                try
                {
                    ResponseDocumentBase kazkommertsbankResponse;
                    XPathDocument doc = new XPathDocument(new StringReader(response));
                    XPathNavigator nav = doc.CreateNavigator();
                    if(nav.SelectSingleNode("//response/error") != null)
                    {
                        kazkommertsbankResponse = new PaymentErrorDocument(response);
                        if(kazkommertsbankResponse.SuccessfulParsed)
                            return kazkommertsbankResponse;
                    }
                    else if(nav.SelectSingleNode("//document/bank") != null)
                    {
                        kazkommertsbankResponse = new PaymentSuccessDocument(response);
                        if(kazkommertsbankResponse.SuccessfulParsed)
                            return kazkommertsbankResponse;
                    }
                    else
                        return null;
                }
                catch
                {
                    return null;
                }
            }
            return null;
        }
    }
}